import { Tools } from "@/utils";
import { RouteRecordRaw } from "vue-router";

//const files = require.context('../views/',true,/.vue/);
const files = import.meta.glob('@/views/**/*.vue');
//const filesArr = files.keys();
const filesArr = Object.keys(files);

/**
 * 路由meta对象参数说明
 * meta: {
 *      title:          菜单栏及 tagsView 栏、菜单搜索名称（国际化）
 *      isLogin：       是否必须要登录才能查看，开启，`isLogin：:true`
 *      isLink：        是否超链接菜单，开启外链条件，`1、isLink:true 2、链接地址不为空`
 *      isHide：        是否隐藏此路由
 *      isKeepAlive：   是否缓存组件状态
 *      isAffix：       是否固定在 tagsView 栏上
 *      isIframe：      是否内嵌窗口，，开启条件，`1、isIframe:true 2、链接地址不为空`
 *      roles：         当前路由权限标识，取角色管理。控制路由显示、隐藏。超级管理员：admin 普通角色：common
 *      icon：          菜单、tagsView 图标，阿里：加 `iconfont xxx`，fontawesome：加 `fa xxx`
 * }
 */

/**
 * 定义动态路由
 * @description 未开启 isRequestRoutes 为 true 时使用（前端控制路由），开启时第一个顶级 children 的路由将被替换成接口请求回来的路由数据
 * @description 各字段请查看 `/@/views/system/menu/component/addMenu.vue 下的 ruleForm`
 * @returns 返回路由菜单数据
 */

//单个路由标题
const titleValue:{
    [key:string]:string
}={
};
//不用跳转登录页面
const isLoginPath = [
	'Login',
];
//该路由是否隐藏
const isHidePath = [
	'Login'
];
//该路由是否隐藏
const isLinkValue:{
    [key:string]:string|Boolean
} = {
};
//是否缓存组件状态
const isKeepAlivePath = [
	'Login'
];
//是否固定在tagsView栏上
const isAffixPath = [
	'Home'
];
//是否内嵌窗口
const isIframeValue:{
    [key:string]:string|Boolean
} = {
};
//超级管理员：admin 普通角色：common
const rolesValue:{
    [key:string]:string[]
} = {
};
//图标
const iconValue:{
    [key:string]:string
} = {
};

//静态路由文件夹
const StaticRoutes=[
	'Login','Error'
]

//带参数的路由
const ParamsName:{
    [key:string]:string
}={
};

//设置路由对象,分children
const routerMain:{
	dynamic:RouteRecordRaw,
	static:RouteRecordRaw[]
}={
	dynamic:{
		path:"/",
		name:'/',
		redirect: '/home',
		component: ()=>import("@/layout/index.vue")
		,meta:{
			title: "首页",
			isLogin: false,
			isLink:'',
			isHide: false,
			isKeepAlive: true,
			isAffix: false,
			isIframe: false,
			roles: [],
			icon: 'iconfont',
		},
		children:[]
	},
	static:[]
}

const ParentObj={};

for (let i = 0; i < filesArr.length; i++) {
	//原始keys
	const oldKey = filesArr[i];

    const obj = filesArr[i].split('/');
    obj.shift();
    obj.shift();
    
	const nameArr=[];

	//变量定义,
	let title = '';	//标题
	let isLogin = true;	//是否需要登录
	let isHide = false;	//是否隐藏路由
	let isLink:string|Boolean = '';	//是否超链接菜单
	let isKeepAlive = false;
	let isAffix = false;
	let isIframe:string|Boolean = '';
	let roles:string[] = [];
	let icon = '';

	let indexBool = false;
	for (let j = 0; j < obj.length; j++) {
		const x = obj[j].split('.')
		nameArr.push(x[0]);
		if(x[0]=="Index"){
			indexBool = true
		}
	}
	if(nameArr.length>0){
		const str:string = nameArr.join('/');
		let params = '';
		const newStr:string = indexBool?str.split('/Index')[0]:str;

		if(Object.keys(titleValue).includes(newStr)){
			title = titleValue[newStr]
		}
		if(isLoginPath.includes(newStr)){
			isLogin = false
		}
		if(isHidePath.includes(newStr)){
			isHide = true
		}
		if(Object.keys(isLinkValue).includes(newStr)){
			isLink = isLinkValue[newStr]
		}

		if(isKeepAlivePath.includes(newStr)){
			isKeepAlive = true
		}

		if(isAffixPath.includes(newStr)){
			isAffix = true
		}
		
		if(Object.keys(isIframeValue).includes(newStr)){
			isIframe = isIframeValue[newStr]
		}
		if(Object.keys(rolesValue).includes(newStr)){
			roles = rolesValue[newStr]
		}
		if(Object.keys(iconValue).includes(newStr)){
			icon = iconValue[newStr]
		}
		
		if(Object.keys(ParamsName).includes(newStr)){
			params = ParamsName[newStr]
		}
		const routerObj = {
			path:"/"+newStr.toLowerCase()+params,
			name:newStr,
			component: ()=>import('../views/'+str+'.vue')
			,meta:{
				title,
				isLogin,
				isLink,
				isHide,
				isKeepAlive,
				isAffix,
				isIframe,
				roles,
				icon
			},
			children:[]
		};


		if(StaticRoutes.includes(obj[0])){
			routerMain.static.push(routerObj);
		}else{
			//如果文件夹层级,初始化父级必须为Index.vue  //暂时固定3层文件夹 /views/Index/Children/Children
			if(nameArr.length>0){
				if(nameArr.length==1){
					ParentObj[nameArr[0]] = routerObj
				}
				if(nameArr.length>1 && ParentObj[nameArr[0]]){
					if(nameArr.length==2){
						ParentObj[nameArr[0]]['children'][nameArr[1]] = routerObj
					}
					
					if(nameArr.length>2 && ParentObj[nameArr[0]]['children'][nameArr[1]]){
						if(nameArr.length==3){
							ParentObj[nameArr[0]]['children'][nameArr[1]]['children'][nameArr[2]] = routerObj
						}
						if(nameArr.length>3 && ParentObj[nameArr[0]]['children'][nameArr[1]]['children'][nameArr[2]]){
							if(nameArr.length==4){
								ParentObj[nameArr[0]]['children'][nameArr[1]]['children'][nameArr[2]]['children'][nameArr[3]] = routerObj
							}
						}
					}
				}
			}
		}
	}

}
routerMain.static.push({
	path:"/:catchAll(.*)",
	name:'E404',
	component: ()=>import("@/views/Error/404.vue")
	,meta:{
		title: "找不到页面",
		isLogin: false,
		isLink:'',
		isHide: false,
		isKeepAlive: true,
		isAffix: false,
		isIframe: false,
		roles: [],
		icon: 'iconfont',
	}
});
const childRoute = routeChildren(ParentObj);
routerMain.dynamic.children=[...childRoute]

const routeArr:RouteRecordRaw[]=[routerMain.dynamic,...routerMain.static];
export default routeArr;


function routeChildren(obj:any){
	const dynamic:RouteRecordRaw[]=[];
	for(const k in obj){
		const newObj= Object.assign({},obj[k]);
		newObj['children'] = [];
		if(obj[k]['children']){
			for(const j in obj[k]['children']){
				const obj2 = obj[k]['children'][j];
				const newObj2= Object.assign({},obj2);
				newObj2['children'] = [];
				
				if(obj2['children']){
					for(const i in obj2['children']){
						const obj3 = obj2['children'][i];
						const newObj3= Object.assign({},obj3);
						newObj3['children'] = [];

						if(obj3['children']){
							for(const x in obj3['children']){
								const obj4 = obj3['children'][x];
								const newObj4= Object.assign({},obj4);
								newObj4['children'] = [];
								//手动循环
								newObj3['children'].push(newObj4);
							}
						}

						newObj2['children'].push(newObj3);
					}
				}
				newObj['children'].push(newObj2);
			}
		}
		const ObjRouter:RouteRecordRaw = newObj;
		dynamic.push(ObjRouter)
	}
	return dynamic;
}